package com.dashunwms_aohe.http;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dashunwms_aohe.http.res.GetDSDataRes;
import com.dashunwms_aohe.http.res.UploadBillRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j(topic = "DSHttpServerImpl")
public class DSHttpServerImpl implements DSHttpService {
    @Value("${ds.commonUrl}")
    private String url;

    @Override
    public UploadBillRes HttpPostReq_UploadBill(String urls, String body) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("LogisticsOrderH", JSONObject.parseObject(body));
        jsonArray.add(jsonObject);
        log.info("上传数据到大舜报文:" + StringEscapeUtils.unescapeJavaScript(jsonArray.toJSONString()));
        String post = HttpUtil.post(url + urls, StringEscapeUtils.unescapeJavaScript(jsonArray.toJSONString()));
        log.info("上传数据到大舜,大舜返回报文:" + post);
        UploadBillRes uploadBillRes = null;
        try {
            uploadBillRes = JSONObject.parseObject(post, UploadBillRes.class);
        } catch (Exception e) {
            log.error("上传数据到大舜返回结果集解析报错" + e.toString());
            uploadBillRes = new UploadBillRes();
            uploadBillRes.getResponse().setRequest(false);
            UploadBillRes.ResponseDTO.ResultDTO resultDTO = new UploadBillRes.ResponseDTO.ResultDTO();
            resultDTO.setReason("上传数据到大舜返回结果集解析报错,返回的报文为:" + post);
            uploadBillRes.getResponse().getResult().add(resultDTO);
        }
        return uploadBillRes;
    }

    @Override
    public List<GetDSDataRes> HttpPostReq_GetData(String urls, String body) {
        log.info("<DSHttpServerImpl>获取大舜数据上传报文:" + body);
        String post = HttpUtil.post(url + urls, body);
        log.info("<DSHttpServerImpl>获取数据大舜返回报文为:" + post);
        List<GetDSDataRes> getDSDataRes = null;
        try {
            getDSDataRes = JSONArray.parseArray(post, GetDSDataRes.class);
            if (getDSDataRes.get(0).getFlag().equals("fail")) {
                getDSDataRes = new ArrayList<>();
            }
        } catch (Exception e) {
            log.error("获取大舜数据返回结果集解析报错" + e.toString());
            GetDSDataRes getDSDataRes22 = new GetDSDataRes();
            getDSDataRes22.setFlag("error");
            getDSDataRes.add(getDSDataRes22);
        }
        return getDSDataRes;
    }
}
